package com.imis.base.util.form.jsonschema;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * JsonSchemaUtil<br>
 * JsonSchema 工具
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2019年03月26日 11:11
 */
@Slf4j
public class JsonSchemaUtil {

    /**
     * 生成JsonSchema
     *
     * @param jsonSchemaDescription - JsonSchema
     * @param propertyList          - 通用 属性
     * @return JSONObject -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/26 14:07
     */
    public static JSONObject getJsonSchema(JsonSchemaDescription jsonSchemaDescription, List<BaseCommonProperty> propertyList) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("$schema", jsonSchemaDescription.getSchema());
        jsonObject.put("type", jsonSchemaDescription.getType());
        jsonObject.put("title", jsonSchemaDescription.getTitle());

        List<String> requiredArr = jsonSchemaDescription.getRequired();
        jsonObject.put("required", requiredArr);

        JSONObject properties = new JSONObject();
        for (BaseCommonProperty baseCommonProperty : propertyList) {
            Map<String, Object> map = baseCommonProperty.getPropertyJson();
            properties.put(map.get("key").toString(), map.get("prop"));
        }
        jsonObject.put("properties", properties);
        // 这里报错: DictVO cannot be cast to DictVO
        log.debug("--- JSONSchema --->" + jsonObject.toJSONString());
        return jsonObject;
    }

    /**
     * 生成JsonSchema 用于子对象
     *
     * @param title         - 子对象描述
     * @param requiredArray - 子对象必填属性名集合
     * @param propertyList  - 子对象属性集合
     * @return JSONObject -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/26 14:07
     */
    public static JSONObject getChildJsonSchema(String title, List<String> requiredArray, List<BaseCommonProperty> propertyList) {
        JSONObject obj = new JSONObject();
        obj.put("type", "object");
        obj.put("view", "tab");
        obj.put("title", title);
        if (requiredArray == null) {
            requiredArray = new ArrayList<>();
        }
        obj.put("required", requiredArray);

        JSONObject properties = new JSONObject();
        for (BaseCommonProperty baseCommonProperty : propertyList) {
            Map<String, Object> map = baseCommonProperty.getPropertyJson();
            properties.put(map.get("key").toString(), map.get("prop"));
        }
        obj.put("properties", properties);
        log.debug("--- JSONSchema --->" + obj.toString());
        return obj;
    }

}
